﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Sita.Data.Repositories;
using Sita.Entities;

namespace Sita.MainModule.Services
{
    public class DeliveryNoteService
    {
        DeliveryNoteRepository DeliveryNoteRepository;
        ReplacementService ReplacementService;

        public DeliveryNoteService()
        {
            DeliveryNoteRepository = new DeliveryNoteRepository();
            ReplacementService = new ReplacementService();
        }

        public IList<DeliveryNote> GetPaginatedDeliveryNotesByBussinesUnitID(int businessUnitID, int pageIndex, int pageSize, string sortColumn, bool ascending, out int totalRows)
        {
            return DeliveryNoteRepository.GetPaginatedByBusinessUnitID(businessUnitID, pageIndex, pageSize, sortColumn, ascending, out totalRows);
        }

        public DeliveryNote GetDeliveryNoteByIDWithItemsAndCustomer(int deliveryNoteID)
        {
            return DeliveryNoteRepository.GetByIDWithItemsAndCustomer(deliveryNoteID);
        }

        public DeliveryNote GetDeliveryNoteByIDWithItems(int deliveryNoteID)
        {
            DeliveryNote deliveryNote = DeliveryNoteRepository.GetByIDWithItems(deliveryNoteID);
            foreach (DeliveryNoteReplacement item in deliveryNote.DeliveryNoteReplacements)
            {
                deliveryNote.DeliveryNoteTotalPrice += item.TotalPrice;
            }

            return deliveryNote;
        }

        public bool ModifyDeliveryNote(DeliveryNote deliveryNote)
        {
            DeliveryNoteRepository.Modify(deliveryNote);

            DeliveryNoteRepository.StoreContext.Commit();

            return true;
        }

        public void AddDeliveryNote(DeliveryNote deliveryNote)
        {
            DeliveryNoteRepository.Add(deliveryNote);

            DeliveryNoteRepository.StoreContext.Commit();
        }

        public IList<DeliveryNote> GetAvailableDeliveryNotesByCustomerID(int customerID)
        {
            return DeliveryNoteRepository.GetAvailableByCustomerID(customerID);
        }

        /// <summary>
        /// Juan Pablo Guardia. 2014-08-08
        /// Descuenta Del stock las repuestos a consumir en el remito. Si la operación es exitosa bloquea el Remito
        /// Si hay algun problema en un item la operación devuelve un mensaje de error.
        /// </summary>
        /// <param name="deliveryNoteID"></param>
        /// <returns></returns>
        public string ValidateStockAndLock(int deliveryNoteID)
        {
            bool LockReplacementSuccess;
            bool SaveReplacementSucess;
            LockReplacementSuccess = false;
            SaveReplacementSucess = false;
            List<Replacement> LoadReplamentList;
            string Result = string.Empty;
            LoadReplamentList = new List<Replacement>();
            
            DeliveryNote LoadDeliveryNote = DeliveryNoteRepository.GetByIDWithItems(deliveryNoteID);

            if (LoadDeliveryNote.Blocked)
            {
                Result = "LOCKED";
                return Result;
            }

            foreach (var item in LoadDeliveryNote.DeliveryNoteReplacements)
            {
                Replacement LoadReplacement = ReplacementService.GetReplacementByID(item.ReplacementID);

                if (LoadReplacement != null)
                {
                    if (LoadReplacement.Stock.HasValue)
                    {
                        if ((LoadReplacement.Stock.Value - item.Quantity) >= 0)
                        {
                            LoadReplacement.Stock = LoadReplacement.Stock.Value - item.Quantity;
                            LoadReplacement.LastSellDate = DateTime.Now;
                            LoadReplamentList.Add(LoadReplacement);
                            LockReplacementSuccess = true;
                        }
                        else
                        {
                            LockReplacementSuccess = false;
                            Result = string.Format("El repuesto {0} - {1} tiene un stock de : {2}. Stock Insuficiente.", LoadReplacement.ReplacementID, LoadReplacement.Name, LoadReplacement.Stock.Value);
                        }
                    }
                    else
                    {
                        LockReplacementSuccess = false;
                        Result = string.Format("El repuesto {0} - {1} no tiene stock definido.", LoadReplacement.ReplacementID, LoadReplacement.Name);
                    }
                }
                else 
                {
                    LockReplacementSuccess = false;
                    Result = string.Format("El item {0} no pudo ser cargado.",item.ReplacementID);
                }

                if (!LockReplacementSuccess)
                {
                    return Result;
                }
                
            }
            if (LockReplacementSuccess)
            {
                foreach (var item in LoadReplamentList)
                {
                    SaveReplacementSucess =  ReplacementService.ModifyReplacement(item);

                    if (!SaveReplacementSucess)
                    {
                        Result = string.Format("No se pudo actualizar el repuesto {0} - {1}", item.ReplacementID, item.Name);
                        return Result;
                    }

                }
            
            }
            if (SaveReplacementSucess)
            {
                LoadDeliveryNote.Blocked = true;
                this.ModifyDeliveryNote(LoadDeliveryNote);
                Result = "SUCCESS";
            }
            
                

            return Result;
        }

        public IList<DeliveryNote> GetPaginatedDeliveryNotesByFilter(int businessUnitID, int pageIndex, int pageSize, string sortColumn, bool ascending, int customerID, int deliveryNoteID, out int totalRows)
        {
            return DeliveryNoteRepository.GetPaginatedByFilter(businessUnitID, pageIndex, pageSize, sortColumn, ascending, customerID, deliveryNoteID, out totalRows);
        }
    }
}
